import { useEffect, useState } from 'react';
import useGetUserInfo from './useGetUserInfo.ts';
import { getUserInfoService } from '../service/user.ts'
import { useRequest } from 'ahooks'
import { useDispatch } from 'react-redux';
import { loginReducer } from '../store/userReducer.ts';
const useLoadUserData = ()=>{
    const [waitingUserData, setWaitingUserData] = useState(true)
    const { username} = useGetUserInfo()
    const dispatch = useDispatch()

    // ajax加载完用户信息之后，放在 redux 中,不用返回
    const { run } = useRequest(getUserInfoService,{
        manual: true,
        onSuccess:(res)=>{
            const { username, nickname } = res
            // 存储到 redux store
            dispatch(loginReducer({username, nickname}))
        },
        onFinally(){
            setWaitingUserData(false)
        }
    })

    useEffect(()=>{
        
        // 如果有了用户信息,就不用管了
        if(username){
            setWaitingUserData(false)
            return 
        }else { // 没有就用ajax加载
            run()
        }
    },[username,run])
    return { waitingUserData }
}

export default useLoadUserData